package com.example.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.common.Result;
import com.example.entity.User;
import com.example.service.UserService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/selectAll")
    public Result selectAll(User user) {
        List<User> userList = userService.selectAll(user);
        return Result.success(userList);
    }

    //新增信息
    @PostMapping("/add")
    public Result add(@RequestBody User user) {   //@RequestBody 接收前端传来的json，post、put、delete可用，get不能用
        userService.add(user);
        return Result.success();
    }

    //编辑信息
    @PutMapping("/update")
    public Result update(@RequestBody User user) {   //@RequestBody 接收前端传来的json，post、put、delete可用，get不能用
        userService.update(user);
        return Result.success();
    }

    //删除信息
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {  //@PathVariable 接收前端传来的路径参数
        userService.deleteById(id);
        return Result.success();
    }

    //通过id查找
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable String id) {  //@PathVariable 接收前端传来的路径参数
        User user = userService.selectById(id);
        userService.selectAll(user);
        return Result.success(user);
    }

    //批量删除
    @DeleteMapping("/deleteBatch")
    public Result delete(@RequestBody List<User> list) {  //@PathVariable 接收前端传来的路径参数
        userService.deleteBatch(list);
        return Result.success();
    }

    //分页功能
    @GetMapping("/selectPage")
    public Result selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             User user) {
        PageInfo<User> pageInfo = userService.selectPage(pageNum, pageSize, user);
        System.out.println("分页结果：" + pageInfo); // 调试日志
        return Result.success(pageInfo);
    }

    //excel批量导出
    @GetMapping("/export")
    public void exportData(User user, HttpServletResponse response) throws Exception {
        System.out.println("前端传入 idsStr: " + user.getIds()); // 查看是否接收到参数
        System.out.println("转换后 idsArr: " + Arrays.toString(user.getIdsArr()));
        String ids = user.getIds();
        if (StrUtil.isNotBlank(ids)) {
            String[] idsArr = ids.split(",");
            user.setIdsArr(idsArr);
        }
        //先获取所有数据
        List<User> userList = userService.selectAll(user);
        //getWriter()默认创建xls格式的excel文件，使用getWriter(true)创建xlsx格式文件
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("username", "账号");
        writer.addHeaderAlias("name", "昵称");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("email", "邮箱");
        // 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
        writer.setOnlyAlias(true);
        // 合并单元格后的标题行，使用默认标题样式
        //writer.merge(3, "校园交友论坛用户信息");
        //写出数据
        writer.write(userList,true);
        //导出为xlxs文件,response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String filename = URLEncoder.encode("校园交友论坛用户信息", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition","attachment;filename=" + filename + ".xlsx");
        ServletOutputStream out=response.getOutputStream();
        writer.flush(out, true);
        //关闭writer，释放内存
        writer.close();
        IoUtil.close(out);
    }

    //从excel导入
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws Exception {
        //  1. 拿到输入流 构建 reader
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //  2. 通过Reader 读取 excel 里面的数据，默认第一行为标题行，从第二行开始导入
        reader.addHeaderAlias("账号", "username");
        reader.addHeaderAlias("昵称", "name");
        reader.addHeaderAlias("电话", "phone");
        reader.addHeaderAlias("邮箱", "email");
        List<User> list = reader.readAll(User.class);
        // 3. 将数据写到数据库
        for (User user : list) {
            userService.add(user);
        }
        return Result.success();
    }
}
